import { ref, onMounted, onUnmounted, Ref } from 'vue';

const aEventSplit = {
  SocketConnect: {
    target: '',
    info: '网络连接',
  },
  SocketSend: {
    target: '',
    info: '网络连接',
  },
  SocketSendTo: {
    target: '',
    info: '网络连接',
  },
  SocketListen: {
    target: '',
    info: '网络连接',
  },
  WFPTcpConnect: {
    target: '',
    info: '网络连接',
  },
  WFPUdpConnect: {
    target: '',
    info: '网络连接',
  },
  WFPSend: {
    target: '',
    info: '网络连接',
  },
  WFPSendTo: {
    target: '',
    info: '网络连接',
  },
  WFPTcpAccept: {
    target: '<-',
    info: ['远端地址', '本地端口'],
  },
  WFPUdpAccept: {
    target: '<-',
    info: ['远端地址', '本地端口'],
  },
  WFPRecv: {
    target: '<-',
    info: ['远端地址', '本地端口'],
  },
  WFPRecvFrom: {
    target: '<-',
    info: ['远端地址', '本地端口'],
  },
  WFPICMPConnect: {
    target: '',
    info: '远端地址',
  },
  WFPICMPAccept: {
    target: '',
    info: '远端地址',
  },
  WFPICMPSendTo: {
    target: '',
    info: '远端地址',
  },
  WFPICMPRecvFrom: {
    target: '',
    info: '远端地址',
  },
  HTTPRequest: {
    target: '',
    info: ['请求方法', '请求地址'],
  },
  RegSetValue: {
    target: ['|', '='],
    info: ['注册表路径', '注册表键', '注册表值'],
  },
  DeleteValue: {
    target: '|',
    info: ['注册表路径', '注册表键'],
  },
  ExtensionTaskScheduler: {
    target: '|',
    info: ['任务名称', '任务路径', '任务命令行'],
  },
  ExtensionShellMonitor: {
    target: '|',
    info: ['窗口名称', '窗口类名'],
  },
  ExtensionHarddiskDeviceControl: {
    target: '|',
    info: ['IOCTL', '路径'],
  },
};

/**
 * 节点接口
 */
export interface TreeNode {
  id: number;
  pid: number;
  name: string;
  value: number;
  label: string;
  children?: TreeNode[];
}

/**
 * 将扁平数组转换为树形结构
 *
 * @param {TreeNode[]} data 扁平数组数据
 * @returns {TreeNode[]} 树形结构数据
 */
export function utListToTree(data: TreeNode[]): TreeNode[] {
  const map: { [id: number]: TreeNode } = {};
  return data.reduce((acc, item) => {
    map[item.id] = { ...item, value: item.id, label: item.name };
    if (item.pid === 0) {
      // @ts-ignore
      acc.push(map[item.id]);
    } else {
      if (map[item.pid]) {
        (map[item.pid].children ||= []).push(map[item.id]);
      }
    }
    return acc;
  }, []);
}

export function getTruncatedFilename(path, maxLength = 45) {
  // 获取完整文件名
  const fullFilename = path.split('/').pop();

  // 分离文件名和扩展名
  const lastDotIndex = fullFilename.lastIndexOf('.');
  const name = lastDotIndex !== -1 ? fullFilename.slice(0, lastDotIndex) : fullFilename;
  const ext = lastDotIndex !== -1 ? fullFilename.slice(lastDotIndex) : '';

  // 计算允许的文件名长度（考虑扩展名和可能的省略号）
  const allowedNameLength = maxLength - ext.length - 3; // 3 for '...'

  let truncatedName;
  if (name.length > allowedNameLength) {
    // 如果文件名过长，截断并添加省略号
    truncatedName = name.slice(0, allowedNameLength) + '...';
  } else {
    truncatedName = name;
  }

  // 组合截断后的文件名和扩展名
  return truncatedName + ext;
}
/**
 * 获取指定的 URL 参数的值。
 *
 * @param name - 要获取的参数名称。
 * @returns 参数的值，如果参数不存在则返回 null。
 */
export function utGetUrlParameter(name: string): string | null {
  const url = window.location.href;
  const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
  const results = regex.exec(url);

  if (!results) return null;
  if (!results[2]) return '';

  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

/**
 * 获取 URL 中的所有参数，并返回一个包含这些参数的对象。
 */
export function utGetUrlParameters() {
  const params = {};
  const url = window.location.href;
  const queryStringStart = url.indexOf('?');

  if (queryStringStart !== -1) {
    const queryString = url.slice(queryStringStart + 1);
    const pairs = queryString.split('&');

    pairs.forEach((pair) => {
      const [key, value] = pair.split('=');
      if (key) {
        params[decodeURIComponent(key)] = decodeURIComponent(value || '');
      }
    });
  }

  return params;
}

export function usePageHeight(): { pageHeight: Ref<number> } {
  const pageHeight = ref<number>(window.innerHeight);

  const updateHeight = () => {
    pageHeight.value = window.innerHeight;
  };

  onMounted(() => {
    window.addEventListener('resize', updateHeight);
  });

  onUnmounted(() => {
    window.removeEventListener('resize', updateHeight);
  });

  return {
    pageHeight,
  };
}

/**
 * 格式化target的数据信息
 * @param oTarget
 */
export function utParseTarget(oTarget) {
  const rule = aEventSplit[oTarget.event_name];
  if (!rule) {
    return [];
  }
  const target = oTarget.target;
  const info = rule.info;
  if (rule.target === '') {
    return [`${info}：${oTarget.target}`];
  } else if (typeof rule.target === 'string') {
    const parts = target.split(rule.target);
    return parts.map((part, index) => `${info[index]}${part}`);
  } else if (Array.isArray(rule.target)) {
    let parts = [target];
    rule.target.forEach((sep) => {
      parts = parts.flatMap((part) => part.split(sep).filter(Boolean));
    });
    return parts.map((part, index) => `${info[index]}：${part}`).filter(Boolean);
  }
  return [];
}
